<template>
    <div>
        <el-dialog v-model="open" title="设置易损性数据" width="1300px" append-to-body :show-close="false" @close="close">
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" style="margin-top: 15px;"
                :rules="rules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="省" prop="provinceId">
                            <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince"
                                clearable :disabled="isProvince">
                                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="cityId">
                            <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable
                                :disabled="isCity">
                                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区/县" prop="countyId">
                            <el-select v-model="queryParams.countyId" placeholder="请选择区/县" @change="chooseCounty" clearable
                                :disabled="isCounty">
                                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="结构类型" prop="structureType">
                            <el-select v-model="queryParams.structureType" placeholder="请选择" @change="structureTypeChange"
                                clearable>
                                <el-option v-for="item in structureTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                            &nbsp;—&nbsp;
                            <el-select v-model="queryParams.structureType1" placeholder="请选择" clearable>
                                <el-option v-for="item in structureType1Options" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设防情况" prop="fortification">
                            <el-select v-model="queryParams.fortification" placeholder="请选择">
                                <el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <hr>
            <div class="table-wrapper">
                <el-form :inline="true" ref="tableForm1Ref" :model="yearsList" :rules="rules">
                    <h4>年代：</h4>
                    <el-table class="listTable" ref="yearTableRef" border :data="yearsList"
                        :cell-style="{ border: '1px solid #e5ebf7' }"
                        :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                        <el-table-column prop="number" header-align="center" align="center" label="候选值" width="200">
                            <template #default>面积比Ai</template>
                        </el-table-column>
                        <el-table-column v-for="(item, i) in yearsOptions" :key="i" :prop="`year${i}`" header-align="center"
                            align="center" :label="item.label">
                            <template #default="{ row, $index }">
                                <el-form-item :prop="`${$index}.year${i}`" :rules="rules[`year${i}`]">
                                    <el-input type="number" v-model.number="row[`year${i}`]" :step="0.1" clearable
                                        :placeholder="`1/${yearsOptions.length}，请输入小数`" :min="0" :max="1"
                                        style="min-width: 150px;"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
                <el-form :inline="true" ref="tableForm2Ref" :model="useList" :rules="rules">
                    <h4>用途：</h4>
                    <el-table class="listTable" ref="useTableRef" border :data="useList"
                        :cell-style="{ border: '1px solid #e5ebf7' }"
                        :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                        <el-table-column prop="number" header-align="center" align="center" label="候选值" width="200">
                            <template #default>面积比Bj</template>
                        </el-table-column>
                        <el-table-column v-for="(item, i) in useOptions" :key="i" :prop="`tableUse${i}`"
                            header-align="center" align="center" :label="item.label">
                            <template #default="{ row, $index }">
                                <el-form-item :prop="`${$index}.tableUse${i}`" :rules="rules[`tableUse${i}`]">
                                    <el-input type="number" v-model.number="row[`tableUse${i}`]" :step="0.1" clearable
                                        :placeholder="`1/${useOptions.length}，请输入小数`" :min="0" :max="1"
                                        style="min-width: 200px;"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
                <el-form :inline="true" ref="tableForm3Ref" :model="csList" :rules="rules" v-if="!disabledcs">
                    <h4>层数：</h4>
                    <el-table class="listTable" ref="floorTableRef" border :data="csList"
                        :cell-style="{ border: '1px solid #e5ebf7' }"
                        :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                        <el-table-column prop="number" header-align="center" align="center" label="候选值" width="200">
                            <template #default>面积比Ck</template>
                        </el-table-column>
                        <el-table-column v-for="(item, i) in csOptions" :key="i" :prop="`floor${i}`" header-align="center"
                            align="center" :label="item.label">
                            <template #default="{ row, $index }">
                                <el-form-item :prop="`${$index}.floor${i}`" :rules="rules[`floor${i}`]">
                                    <el-input type="number" v-model.number="row[`floor${i}`]" :step="0.1" clearable
                                        :placeholder="`1/${csOptions.length}，请输入小数`" :min="0" :max="1"
                                        style="min-width: 200px;"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">生 成</el-button>
                    <el-button plain @click="close">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getProvince, getChildArea } from "@/api/system/division"
import { saveOrUpdate } from '@/api/basicDataManage/ysxData'
// 状态管理模块
import useDictStore from "@/store/modules/dict";
import { nextTick } from "vue";
const dictStore = useDictStore();
// 当前实例
const { proxy } = getCurrentInstance()

//最多保留N小数 ,N 在 options {decimals: N} 中定义
const structureTypeRules = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请选择结构类型！'));
    } else {
        if (!structureType1Options.value) {
            callback();
        } else {
            if (!queryParams.value.structureType) {
                callback(new Error('请选择二级结构类型！'));
            } else {
                callback();
            }
        }
    }
};

const props = defineProps({
    open: {
        type: Boolean,
        default: false
    },
    fortifyOptions: {
        type: Object,
        default: () => { }
    },
    roleObj: {
        type: Object,
        default: () => { }
    },
    provinceData: {
        type: Array,
        default: []
    }
})

// 变量
const queryData = reactive({
    queryParams: {},
    // 年代
    yearsOptions: dictStore.yearsOptions || [],
    // 用途
    useOptions: dictStore.useOptions || [],
    useOptions1: [],
    // 层数
    csOptions: dictStore.csOptions || [],
    // 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
    // 结构类型
    structureTypeOptions: dictStore.structureTypeOptions || [],
    structureType1Options: [],
    // 表格
    yearsList: [{}],
    useList: [{}],
    csList: [{}],
    // 表单验证规则
    rules: {
        provinceId: [{ required: true, message: '请选择省', trigger: 'change' }],
        cityId: [{ required: true, message: '请选择市', trigger: 'change' }],
        countyId: [{ required: true, message: '请选择区/县', trigger: 'change' }],
        structureType: [{ required: true, trigger: 'change', validator: structureTypeRules, }],
        fortification: [{ required: true, message: '请选择设防情况', trigger: 'change' }],
        year0: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        year1: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        year2: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        year3: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        year4: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        year5: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],

        tableUse0: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        tableUse1: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        tableUse2: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],

        floor0: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        floor1: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
        floor2: [
            // { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', min: 0, max: 1, message: '请输入0-1之间的小数' }
        ],
    },
})
const {
    queryParams,
    structureTypeOptions,
    structureType1Options,
    fortificationOptions,
    yearsOptions,
    useOptions,
    useOptions1,
    csOptions,
    yearsList,
    useList,
    csList,
    rules,
} = toRefs(queryData)

// 省市县
const provinceData = ref([]);
const cityData = ref([])
const areaData = ref([])

const emits = defineEmits(['update:open', 'createSuccess'])


// 以下结构对应全楼层
const arrStructure = ['钢筋混凝土结构', '钢结构', '组合结构'];

// 选择结构类型
const disabledcs = ref(false);
const structureTypeChange = (val) => {
  const structureTypes = structureTypeOptions.value.find(
    (item) => item.value === val
  );
  if (structureTypes) {
    structureType1Options.value = structureTypes.children;
  }
    queryParams.value.structureType1 = ''; // 切换一级下拉，置空二级下拉
    // 设防情况
	queryParams.value.fortification = '';
	// 清空用途
	useOptions1.value = [];
	// 设防情况
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
		csOptions.value = dictStore.csOptions;
		disabledcs.value = false;
		// 用途处理
		useOptions.value = dictStore.useOptions;
	} else if(val=='组合结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
		disabledcs.value = false;
		// 用途处理
		useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '公寓',
                        label: '公寓'
                    },
                    {
                        value: '学生和职工集体宿舍',
                        label: '学生和职工集体宿舍'
                    },
                    {
                        value: '宾馆',
                        label: '宾馆'
                    },
                    {
                        value: '招待所',
                        label: '招待所'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '办公室',
                        label: '办公室'
                    },
                ]
            },
        ]
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
		disabledcs.value = false;
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		// 层数处理
		disabledcs.value = true;
		csOptions.value = [];
		// 用途
		if(val=='土木结构'||val=='木结构'||val=='其他'){
			useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅲ类',
                label: '第Ⅲ类',
                children: [
                    {
                        value: '除I、II类以外',
                        label: '除I、II类以外'
                    }
                ]
            }
        ]
		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}else{
			useOptions.value = [
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '生产车间',
                        label: '生产车间'
                    },
                ]
            },
        ]
		}
	}
};

// 获取省份列表
// const getProvinceData = () => {
//     getProvince().then(res => {
//         if (res.code == 200) {
//             provinceData.value = res.data
//         }
//     })
// }
// 选择省
const chooseProvince = (value) => {
    queryParams.value.cityId = null
    queryParams.value.countyId = null
    queryParams.value.city = null
    queryParams.value.county = null
    cityData.value = []
    areaData.value = []
    queryParams.value.province = provinceData.value.find(item => item.id == value)?.name
    getChildArea(value).then(response => {
        cityData.value = response.data
    })
}
// 选择市
const chooseCity = (value) => {
    queryParams.value.countyId = null
    queryParams.value.county = null
    areaData.value = []
    queryParams.value.city = cityData.value.find(item => item.id == value)?.name
    getChildArea(value).then(response => {
        areaData.value = response.data
    })
}
// 选择区县
const chooseCounty = (value) => {
    queryParams.value.county = areaData.value.find(item => item.id == value)?.name
}

// 提交上传文件
const submitFileForm = () => {
    proxy.$refs['queryRef'].validate(async (valid, fields) => {
        if (valid) {
            let arrYears = [];
           	// 年代，若表单没有选择则需要列表输入
			if ( yearsList.value) {
				// 表单验证
				const tableForm1Valid = proxy.$refs['tableForm1Ref'].validate(async (valid, fields) => { valid, fields });
				if (!tableForm1Valid) {
					return;
				}
				// 年代
				const cur = yearsList.value[0];
				let arr = [];
				if (cur) {
					arr = Object.values(cur);
				}
				// 没有值的部分，均分补足，总比为100%
				if (arr.length < 6) {
					let sum = 0;
					if (arr.length) {
						sum = arr.reduce((prev, next) => {
							return Number(prev || 0) + Number(next || 0);
						})
					}
					// 判断差值并取平均
					let diffAverage = null;
					if(queryParams.value.structureType=='土木结构'){
						if (sum == 1) {
							diffAverage = Number(Number((1 - sum) / (4 - arr.length)).toFixed(10));
							arrYears = [
								cur.year0 || cur.year0 == '0' ? cur.year0 : diffAverage,
								cur.year1 || cur.year1 == '0' ? cur.year1 : diffAverage,
								cur.year2 || cur.year2 == '0' ? cur.year2 : diffAverage,
								cur.year3 || cur.year3 == '0' ? cur.year3 : diffAverage,
								// cur.year4 || cur.year4 == '0' ? cur.year4 : diffAverage,
								// cur.year5 || cur.year5 == '0' ? cur.year5 : diffAverage,
							]
						} else {
							proxy.$modal.msgWarning("输入的年代面积比Ai之和不等于100%，请检查输入占比值！");
							return;
						}
					}else{
						if (sum == 1) {
							diffAverage = Number(Number((1 - sum) / (6 - arr.length)).toFixed(10));
							arrYears = [
								cur.year0 || cur.year0 == '0' ? cur.year0 : diffAverage,
								cur.year1 || cur.year1 == '0' ? cur.year1 : diffAverage,
								cur.year2 || cur.year2 == '0' ? cur.year2 : diffAverage,
								cur.year3 || cur.year3 == '0' ? cur.year3 : diffAverage,
								cur.year4 || cur.year4 == '0' ? cur.year4 : diffAverage,
								cur.year5 || cur.year5 == '0' ? cur.year5 : diffAverage,
							]
						} else {
							proxy.$modal.msgWarning("输入的年代面积比Ai之和不等于100%，请检查输入占比值！");
							return false;
						}
					}
				} else {
					if(queryParams.value.structureType=='土木结构'){
						arrYears = [
							cur.year0 || 0,
							cur.year1 || 0,
							cur.year2 || 0,
							cur.year3 || 0,
							// cur.year4 || 0,
							// cur.year5 || 0,
						]
					}else{
						arrYears = [
							cur.year0 || 0,
							cur.year1 || 0,
							cur.year2 || 0,
							cur.year3 || 0,
							cur.year4 || 0,
							cur.year5 || 0,
						]
					}
				}
			} else {
				proxy.resetForm("tableForm1Ref");
			}

            let arrUse = [];
            // 用途，若表单没有选择则需要列表输入
            if (useList.value) {
                // 表单验证
                const tableForm2Valid = proxy.$refs['tableForm2Ref'].validate(async (valid, fields) => { valid, fields });
                if (!tableForm2Valid) {
                    return false;
                }
                // 用途
				const cur = useList.value[0];
				let arr = [];
				if (cur) {
					arr = Object.values(cur);
				}
				// 组合结构
				if(queryParams.value.structureType=='组合结构'||queryParams.value.structureType=='土木结构'||queryParams.value.structureType=='木结构'||queryParams.value.structureType=='其他'){
					// 用途可输入数量
					const useLen0 = useOptions.value[0].children.length;
					const useLen1 = useOptions.value[1].children.length;
					const useLen = useLen0 + useLen1;
					let arrUse1 = [];
					let arrUse2 = [];
					const use0 = useList.value[0].tableUse0;
					const use1 = useList.value[0].tableUse1;
					let sum = 0;
					let len = useLen;
					if (use0 || use0 == '0') {
						const average0 = Number((use0 / useLen0).toFixed(10));
						for (let i = 0; i < useLen0; i++) {
							arrUse1.push(average0);
						}
						sum += Number(use0 || 0);
						len -= useLen0;
					}
					if (use1 || use1 == '0') {
						const average1 = Number((use1 / useLen1).toFixed(10));
						for (let i = 0; i < useLen1; i++) {
							arrUse2.push(average1);
						}
						sum += Number(use1 || 0);
						len -= useLen1;
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1) {
						if (len > 0) {
							diffAverage = Number(Number((1 - sum) / len).toFixed(10));
							if (arrUse1.length == 0) {
								for (let i = 0; i < useLen0; i++) {
									arrUse1.push(diffAverage);
								}
							}
							if (arrUse2.length == 0) {
								for (let i = 0; i < useLen1; i++) {
									arrUse2.push(diffAverage);
								}
							}
						}
						arrUse = [
							...arrUse1,
							...arrUse2,
						]
					} else {
						proxy.$modal.msgWarning("输入的用途面积比Bj之和不等于100%，请检查输入占比值！");
						return;
					}
				}else if(queryParams.value.structureType=='工业厂房'){
					// 用途可输入数量
					const useLen0 = useOptions.value[0].children.length;
					const useLen = useLen0;
					let arrUse1 = [];
					const use0 = useList.value[0].tableUse0;
					let sum = 0;
					let len = useLen;
					if (use0 || use0 == '0') {
						const average0 = Number((use0 / useLen0).toFixed(10));
						for (let i = 0; i < useLen0; i++) {
							arrUse1.push(average0);
						}
						sum += Number(use0 || 0);
						len -= useLen0;
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1) {
						if (len > 0) {
							diffAverage = Number(Number((1 - sum) / len).toFixed(10));
							if (arrUse1.length == 0) {
								for (let i = 0; i < useLen0; i++) {
									arrUse1.push(diffAverage);
								}
							}
						}
						arrUse = [
							...arrUse1,
						]
					} else {
						proxy.$modal.msgWarning("输入的用途面积比Bj之和不等于100%，请检查输入占比值！");
						return;
					}
				}else{
					// 用途可输入数量
					const useLen0 = useOptions.value[0].children.length;
					const useLen1 = useOptions.value[1].children.length;
					const useLen2 = useOptions.value[2].children.length;
					const useLen = useLen0 + useLen1 + useLen2;
					let arrUse1 = [];
					let arrUse2 = [];
					let arrUse3 = [];
					const use0 = useList.value[0].tableUse0;
					const use1 = useList.value[0].tableUse1;
					const use2 = useList.value[0].tableUse2;
					
					let sum = 0;
					let len = useLen;
					if (use0 || use0 == '0') {
						const average0 = Number((use0 / useLen0).toFixed(10));
						for (let i = 0; i < useLen0; i++) {
							arrUse1.push(average0);
						}
						sum += Number(use0 || 0);
						len -= useLen0;
					}
					if (use1 || use1 == '0') {
						const average1 = Number((use1 / useLen1).toFixed(10));
						for (let i = 0; i < useLen1; i++) {
							arrUse2.push(average1);
						}
						sum += Number(use1 || 0);
						len -= useLen1;
					}
					if (use2 || use2 == '0') {
						const average2 = Number((use2 / useLen2).toFixed(10));
						for (let i = 0; i < useLen2; i++) {
							arrUse3.push(average2);
						}
						sum += Number(use2 || 0);
						len -= useLen2;
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1) {
						if (len > 0) {
							diffAverage = Number(Number((1 - sum) / len).toFixed(10));
							if (arrUse1.length == 0) {
								for (let i = 0; i < useLen0; i++) {
									arrUse1.push(diffAverage);
								}
							}
							if (arrUse2.length == 0) {
								for (let i = 0; i < useLen1; i++) {
									arrUse2.push(diffAverage);
								}
							}
							if (arrUse3.length == 0) {
								for (let i = 0; i < useLen2; i++) {
									arrUse3.push(diffAverage);
								}
							}
						}
						arrUse = [
							...arrUse1,
							...arrUse2,
							...arrUse3,
						]
					} else {
						proxy.$modal.msgWarning("输入的用途面积比Bj之和不等于100%，请检查输入占比值！");
						return;
					}
				}
            } else {
                proxy.resetForm("tableForm2Ref");
            }

            let arrFloors = [];
            // 层数，若表单没有选择则需要列表输入
            if (csList.value) {
                // 表单验证
                const tableForm3Valid = proxy.$refs['tableForm3Ref'].validate(async (valid, fields) => { valid, fields });
                if (!tableForm3Valid) {
                    return;
                }
                // 层数
                const cur = csList.value[0];
                let arr = [];
                if (cur) {
                    arr = Object.values(cur);
                }
              	// 层数可输入数量
				const csLen = csOptions.value.length;
				// 没有值的部分，均分补足，总比为100%
				if (arr.length < csLen&& csLen<2) {
					let sum = 0;
					if (arr.length) {
						sum = arr.reduce((prev, next) => {
							return Number(prev || 0) + Number(next || 0);
						})
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1) {
						diffAverage = Number(Number((1 - sum) / (csLen - arr.length)).toFixed(10));
						arrFloors = [
							cur.floor0 || cur.floor0 == '0' ? cur.floor0 : diffAverage,
							// cur.floor1 || cur.floor1 == '0' ? cur.floor1 : diffAverage,
						]
					} else {
						proxy.$modal.msgWarning("输入的层数面积比Ck之和不等于100%，请检查输入占比值！");
						return;
					}
				}else if(csLen>1){
					let sum = 0;
					if (arr.length) {
						sum = arr.reduce((prev, next) => {
							return Number(prev || 0) + Number(next || 0);
						})
					}
					// 判断差值并取平均
					let diffAverage = null;
					if (sum == 1) {
						diffAverage = Number(Number((1 - sum) / (csLen - arr.length)).toFixed(10));
						arrFloors = [
							cur.floor0 || cur.floor0 == '0' ? cur.floor0 : diffAverage,
							cur.floor1 || cur.floor1 == '0' ? cur.floor1 : diffAverage,
						]
						// 有9层以上
						if (csLen == 3) {
							arrFloors.push(cur.floor2 || cur.floor2 == '0' ? cur.floor2 : diffAverage);
						}
					} else {
						proxy.$modal.msgWarning("输入的层数面积比Ck之和不等于100%，请检查输入占比值！");
						return;
					}					
				} else {
					arrFloors = [
						cur.floor0 || 0,
						cur.floor1 || 0,
					]
					// 有9层以上
					if (csLen == 3) {
						arrFloors.push(cur.floor2 || 0);
					}
				}
            } else {
                proxy.resetForm("tableForm3Ref");
            }
            proxy.$modal.loading("正在生成，请稍候...");
            saveOrUpdate({
                // 基础信息
                ...queryParams.value,
                // 年份列表
                yearsList: arrYears,
                // 用途列表
                useList: arrUse,
                // 层数列表
                csList: arrFloors,
                roleType:roleType.value
            }).then((res) => {
                const { code, data } = res;
                if (code === 200 && data) {
                    console.log(data);
                    emits('createSuccess', data)
                    close();
                    proxy.$modal.closeLoading()
                    // 根据查询情况设置矩阵表格
                    // setMatrixTableData(data);
                }
            }).catch(err => {
                console.log(err.message);
                proxy.$modal.closeLoading()
            });
        }
    });
}

const close = () => {
    emits('update:open', false)
}
const isProvince = ref(false);
const isCity = ref(false);
const isCounty = ref(false);
const roleType = ref('')

const reset = () =>{
    proxy.resetForm("queryRef");
    queryParams.value.structureType1 = '';
    proxy.resetForm("tableForm1Ref");
    proxy.resetForm("tableForm2Ref");
    proxy.resetForm("tableForm3Ref");
}
// 挂载
onMounted(async () => {
    nextTick(() => {
        provinceData.value = props.provinceData;
        const data = props.roleObj.value
        switch (data.role) {
            case 'qh_gj_role': // 国家级
                isProvince.value = false;
                isCity.value = false;
                isCounty.value = false;
                roleType.value =  '0'
                break;
            case 'qh_province_role': // 省级
                isProvince.value = true;
                queryParams.value.provinceId = data.provinceId;
                queryParams.value.province = provinceData.value.find(item => item.id == data.provinceId)?.name
                chooseProvince(queryParams.value.provinceId)
                isCity.value = false;
                isCounty.value = false;
                roleType.value =  '1'
                break;
            case 'qh_city_role':
                isProvince.value = true; // 市级
                isCity.value = true;
                queryParams.value.provinceId = data.provinceId;
                queryParams.value.cityId = data.cityId;
                getChildArea(queryParams.value.provinceId).then(response => {
					cityData.value = response.data;
					chooseCity(data.cityId)
				})
                isCounty.value = false;
                roleType.value =  '2'
                break;
            case 'ph_county_role':
                isProvince.value = true; // 县级
                isCity.value = true;
                isCounty.value = true;
                queryParams.value.provinceId = data.provinceId;
                queryParams.value.cityId = data.cityId;
                queryParams.value.countyId = data.countyId;
                getChildArea(queryParams.value.provinceId).then(response => {
					cityData.value = response.data;
					chooseCity(data.cityId)
				})
                roleType.value =  '3'
                break;
            default:
                break;
        }
    })

    // 获取省份列表
    // getProvinceData();
})

defineExpose({
  reset
});
</script>

<style lang="scss" scoped>
// 列表页，表格样式
.table-wrapper {
    position: relative;

    h4 {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-color-primary);
    }

    .buttonGroup {
        position: absolute;
        right: 0px;
        top: -10px;
    }

    // 表格中新增的行/列样式
    .add-row,
    .add-column {
        // background-color: var(--el-color-success-light-9);
        background-color: #f2f2f2;
    }

    .table-content {
        display: flex;

        .table-left {
            width: 98%;
        }

        // 表格右侧新增列
        .table-right {
            button {
                padding: 15px 8px;
                height: 100%;
            }
        }
    }
}</style>